package cn.openea.perpartner.meily.homepagesearch.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.meily.homepagesearch.entity.Task;
import cn.openea.perpartner.meily.homepagesearch.entity.TaskVo;
import cn.openea.perpartner.meily.homepagesearch.mapper.TaskMapper;
import cn.openea.perpartner.meily.homepagesearch.service.ITaskService;
import cn.openea.perpartner.meily.web.entity.Goods;
import cn.openea.perpartner.meily.web.entity.Job;
import cn.openea.perpartner.meily.web.entity.LearningCourse;
import cn.openea.perpartner.meily.web.entity.TaskHall;
import cn.openea.perpartner.meily.web.entity.dto.SearchDto;
import cn.openea.perpartner.meily.web.entity.vo.CourseSeSearchVo;
import cn.openea.perpartner.meily.web.entity.vo.GoodsVo;
import cn.openea.perpartner.meily.web.entity.vo.JobVo;
import cn.openea.perpartner.meily.web.service.IGoodsService;
import cn.openea.perpartner.meily.web.service.IJobService;
import cn.openea.perpartner.meily.web.service.ILearningCourseService;
import cn.openea.perpartner.meily.web.service.ITaskHallService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author rains
 * @since 2023-06-29 15:35
 */
@Service("taskService")
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Resource
    private IJobService jobService;
    @Resource
    private ITaskHallService taskHallService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private ILearningCourseService courseService;

    @Override
    public List<?> selectList(TaskVo vo) {

        List<?> list = new ArrayList<>();

        // 标签。0工作、1生活、2学习
        String tab = vo.getTab();

        // 查询工作
        if("0".equals(tab)){

            // 关键字搜索
            String searchStr = vo.getSearchStr();

            // 1.获取正在招聘的岗位
            LambdaQueryWrapper<Job> jobQueryWrapper = new LambdaQueryWrapper<>();
            if (StrUtil.isNotBlank(searchStr)) {
                jobQueryWrapper.and(wrap -> wrap.like(Job::getJobName, searchStr)
                        .or().like(Job::getKeyword, searchStr)
                        .or().like(Job::getRecruits, searchStr)
                        .or().like(Job::getSalary, searchStr)
                        .or().like(Job::getExperiece, searchStr)
                        .or().like(Job::getDegree, searchStr)
                        .or().like(Job::getType, searchStr)
                        .or().like(Job::getRequirements, searchStr)
                        .or().like(Job::getCompany, searchStr)
                        .or().like(Job::getArea, searchStr)
                        .or().like(Job::getAddress, searchStr)
                        .or().like(Job::getDetails, searchStr)
                        .or().like(Job::getJobTags, searchStr));
            }
            jobQueryWrapper.orderByDesc(Job::getCreateTime);

            // 2.获取正在进行活动（测评/样品）
            LambdaQueryWrapper<TaskHall> taskHallQueryWrapper = new LambdaQueryWrapper<>();
            // 关键字搜索
            if (StrUtil.isNotBlank(searchStr)) {
                taskHallQueryWrapper.and(wrap -> wrap.eq(TaskHall::getTaskNumber, searchStr)
                        .or().like(TaskHall::getTaskName, searchStr)
                        .or().like(TaskHall::getTaskDetail, searchStr)
                        .or().like(TaskHall::getTaskPrice, searchStr)
                        .or().like(TaskHall::getTaskType, searchStr)
                        .or().like(TaskHall::getTaskKeyword, searchStr)
                        .or().like(TaskHall::getTaskLabel, searchStr)
                        .or().like(TaskHall::getCreateUserName, searchStr));
            }
            taskHallQueryWrapper.orderByDesc(TaskHall::getCreateTime);
            list = baseMapper.getJobAndTaskHallList(jobQueryWrapper, taskHallQueryWrapper);
        }

        // 查询商品
        if("1".equals(tab)){
            // 1.获取已上架的商品
            list = getGoods(vo);
        }

        // 查询学习
        if("2".equals(vo.getTab())){
            // 1.获取学习课程
            list = getCourse(vo);
        }

        return list;
    }

    @Override
    public AjaxResult selectWorkList(TaskVo vo) {

        List<?> list = new ArrayList<>();
        // 查询工作
        if("0".equals(vo.getTab())){
            // 1.获取所有正在招聘的岗位
            List<Job> jobList = getAllJob(vo);
            // 2.获取所有正在进行活动（测评/样品）
            List<TaskHall> taskHallList = getAllTaskHall(vo);
            // 3.数据处理
            list = integrateData(jobList, taskHallList);
        }

        List<Task> new_list = new ArrayList<>();
        // 计算需要获取的数据
        int startNum = 0;
        int endNum = 10;
        if(Integer.parseInt(vo.getPageNum()) > 0){
            endNum = Integer.parseInt(vo.getPageNum()) * Integer.parseInt(vo.getPageSize());
            startNum = endNum - Integer.parseInt(vo.getPageSize());
        }

        if(endNum > list.size()){
            endNum = list.size();
        }

        // 按照分页取数据
        for(int i = startNum; i < endNum; i++){
            new_list.add((Task)list.get(i));
        }
        AjaxResult ajaxResult = AjaxResult.success("查询成功！", new_list);
        ajaxResult.put("total", list.size());
        ajaxResult.put("tab", vo.getTab());

        return ajaxResult;
    }

    /**
     * 获取所有的正在招聘的岗位
     * @param vo
     * @return
     */
    private List<Job> getAllJob(TaskVo vo){
        JobVo jobVo = new JobVo();
        jobVo.setSearchStr(vo.getSearchStr());
        jobVo.setStatus("招聘中");
        return jobService.selectList(jobVo);
    }

    /**
     * 获取所有正在进行活动（测评/样品）
     * @param vo
     * @return
     */
    private List<TaskHall> getAllTaskHall(TaskVo vo){
        SearchDto searchDto = new SearchDto();
        searchDto.setSearchStr(vo.getSearchStr());
        searchDto.setCollectType("market");
        return taskHallService.selectList(searchDto);
    }

    /**
     * 整合数据
     * @param jobList
     * @param taskHallList
     * @return
     */
    private List<Task> integrateData(List<Job> jobList, List<TaskHall> taskHallList){

        List<Task> list = new ArrayList<>();

        // 遍历岗位
        for(Job job : jobList){

            String titleLabel = "";// 标题标签
            String titleColor = "";// 标题标签颜色
            if(StrUtil.isNotBlank(job.getJobTop())){
                titleLabel = "热";
                titleColor = "#ffa800";
            } else {
                try {
                    // 这个是新，前提是它不是热的情况下才去判断是不是新（创建时间在一周内）
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    long days = DateUtil.between(sdf.parse(DateUtil.now()), sdf.parse(job.getCreateTime()), DateUnit.DAY);
                    if(days < 8){
                        titleLabel = "新";
                        titleColor = "#ea4d5e";
                    }
                } catch (ParseException e){
                    e.printStackTrace();
                }
            }

            List<String> labels = new ArrayList<>();
            // 工作经验
            if(StrUtil.isNotBlank(job.getExperiece())){
                labels.add(job.getExperiece());
            }

            // 学历要求
            if(StrUtil.isNotBlank(job.getDegree())){
                labels.add(job.getDegree());
            }

            // 工作类型/工作要求
            String type = "";
            if(StrUtil.isNotBlank(job.getType())){
                type +=  job.getType();
            }
            if(StrUtil.isNotBlank(job.getRequirements())){
                type +=  job.getRequirements();
            }
            if(StrUtil.isNotBlank(type)){
                labels.add(type);
            }

            // 关键字
            if(StrUtil.isNotBlank(job.getKeyword())){
                labels.add(job.getKeyword());
            }

            // 图片
            String image = "";
            if("男".equals(job.getAvatar())){
                image = "https://dev-1308272144.cos.ap-guangzhou.myqcloud.com/Meily/img/boy.png";
            }
            if("女".equals(job.getAvatar())){
                image = "https://dev-1308272144.cos.ap-guangzhou.myqcloud.com/Meily/img/girl.png";
            }

            // 额外信息
            JSONObject extraJSON = new JSONObject();
            extraJSON.put("leader", job.getLeader());
            extraJSON.put("posts", job.getPosts());
            extraJSON.put("area", job.getArea());

            Task task = new Task();
            task.setType("0");// 类型。0岗位、1活动(包含测评、样品)、2商品、3学习
            task.setTitle(job.getJobName());// 标题
            task.setSubtitle(job.getCompany());// 副标题
            task.setTitleLabel(titleLabel);// 标题标签
            task.setTitleColor(titleColor);// 标题标签颜色
            task.setPrice(job.getSalary());// 价格
            task.setLabels(String.join(",", labels));// 标签
            task.setLabelsColor("");// 标签颜色
            task.setCouponLabel("");// 优惠券标签
            task.setCreateTime(job.getCreateTime());// 创建时间
            task.setImages(image);// 图片
            task.setBusinessId(String.valueOf(job.getJobId()));// 岗位id
            task.setJumpUrl("/pages_tabbar_contact/index_contact/jobDetails?jobId=" + job.getJobId());// 跳转地址
            task.setExtraJSON(extraJSON);// 额外信息
            list.add(task);

        }

        // 遍历活动
        for(TaskHall taskHall : taskHallList){
            Task task = new Task();
            task.setType("1");// 类型。0岗位、1活动(包含测评、样品)、2商品、3学习
            task.setTitle(taskHall.getTaskName());// 标题
            task.setSubtitle("");// 副标题
            task.setTitleLabel(taskHall.getTaskKeyword());// 标题标签
            task.setTitleColor("#40972f");// 标题标签颜色
            task.setPrice(taskHall.getTaskPrice());// 价格
            task.setLabels(taskHall.getTaskLabel());// 标签
            task.setLabelsColor(taskHall.getTaskColor());// 标签颜色
            task.setCouponLabel(taskHall.getCouponLabel());// 优惠券标签
            task.setCreateTime(taskHall.getCreateTime());// 创建时间
            task.setImages(taskHall.getImageUrl());// 图片
            task.setBusinessId(taskHall.getTaskCurrentId());// 测评id、样品id等
            task.setJumpUrl(taskHall.getTaskUrl());// 跳转地址
            task.setExtraJSON(null);// 额外信息
            list.add(task);
        }

        // 按照时间降序，重新排序
        Collections.sort(list, new Comparator<Task>() {
            @Override
            public int compare(Task task1, Task task2) {
                return task2.getCreateTime().compareTo(task1.getCreateTime());
            }
        });

        return list;

    }

    /**
     * 查询商品
     * @param vo
     * @return
     */
    private List<Goods> getGoods(TaskVo vo){
        GoodsVo goodsVo = new GoodsVo();
        goodsVo.setSearchStr(vo.getSearchStr());
        return goodsService.queryAll(goodsVo);
    }

    /**
     * 查询学习
     * @param vo
     * @return
     */
    private List<LearningCourse> getCourse(TaskVo vo){
        CourseSeSearchVo searchVo = new CourseSeSearchVo();
        searchVo.setSearchStr(vo.getSearchStr());
        return courseService.selectList(searchVo);
    }
}
